'use strict'

const { Controller } = require('egg')

class ColorController extends Controller {
  // 获取全部颜色
  async getColor() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      color: { type: 'string', desc: '颜色' },
      wall_id: { type: 'int', desc: '墙的id' }
    })
    const { color, wall_id } = ctx.request.query
    const Op = app.Sequelize.Op
    // 整理查询条件
    let where = {}
    if (color) where.color = { [Op.like]: `%${color}%` }
    if (wall_id) where.wall_id = wall_id

    let result = await app.model.Color.findAll({
      where,
      include: [
        {
          model: app.model.Wall,
          attributes: ['title']
        }
      ],
      order: [['id', 'DESC']]
    })
    // 获取颜色下留言的数量
    result = JSON.parse(JSON.stringify(result))
    for (let i = 0; i < result.length; i++) {
      result[i].leaveword_count = await app.model.Leaveword.count({
        where: { color_id: result[i].id }
      })
    }
    ctx.apiSuccess(result)
  }
  // 新增颜色
  async createColor() {
    const { ctx, service } = this
    // 参数验证
    ctx.validate({
      wall_id: { type: 'int', required: true, desc: '墙的id' },
      color: { type: 'string', required: true, range: { min: 1, max: 50 }, desc: '颜色' }
    })
    const { wall_id, color } = ctx.request.body
    const colorArr = color.split(',')
    // 背景颜色
    const bg_color =
      colorArr[0].trim() + ',' + colorArr[1].trim() + ',' + colorArr[2].trim() + ',' + '0.3)'
    const result = await service.color.createColor({ wall_id, color, bg_color })
    ctx.apiSuccess(result)
  }
  // 修改颜色
  async updateColor() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      id: { type: 'int', required: true, desc: '颜色id' },
      color: { type: 'string', required: true, range: { min: 1, max: 50 }, desc: '颜色' }
    })
    const { id, color } = ctx.request.body
    // 查询数据库
    const colorObj = await app.model.Color.findOne({ where: { id } })
    if (!colorObj) ctx.throw(400, '该记录不存在')
    const colorArr = color.split(',')
    // 背景颜色
    const bg_color =
      colorArr[0].trim() + ',' + colorArr[1].trim() + ',' + colorArr[2].trim() + ',' + '0.3)'
    const result = await colorObj.update({ color, bg_color }) // 修改颜色

    ctx.apiSuccess(result)
  }
  // 删除颜色
  async deleteColor() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      ids: { type: 'string', required: true, desc: '颜色id' }
    })
    let { ids } = ctx.request.body
    // 整理参数
    ids = ids.split(',').map((id) => parseInt(id))
    const result = await app.model.Color.destroy({ where: { id: ids } })
    ctx.apiSuccess(result)
  }
}

module.exports = ColorController
